package com.ruoyi.market.service.impl;

import com.ruoyi.common.constant.DictConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.market.domain.Goods;
import com.ruoyi.market.mapper.GoodsMapper;
import com.ruoyi.market.service.IGoodsService;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.List;

/**
 * 商品 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class GoodsServiceImpl implements IGoodsService
{
    private static final Logger log = LoggerFactory.getLogger(GoodsServiceImpl.class);

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    /**
     * 根据条件分页查询商品列表
     * 
     * @param goods 商品信息
     * @return 商品信息集合信息
     */
    @Override
    public List<Goods> selectGoodsList(Goods goods)
    {
        return goodsMapper.selectGoodsList(goods);
    }

    /**
     * 通过商品名查询商品
     * 
     * @param goodsTitle 商品名
     * @return 商品对象信息
     */
    @Override
    public Goods selectGoodsByGoodsTitle(String goodsTitle)
    {
        return goodsMapper.selectGoodsByGoodsTitle(goodsTitle);
    }

    /**
     * 通过商品ID查询商品
     * 
     * @param goodsId 商品ID
     * @return 商品对象信息
     */
    @Override
    public Goods selectGoodsById(Long goodsId)
    {
        return goodsMapper.selectGoodsById(goodsId);
    }

    /**
     * 校验商品是否唯一
     *
     * @param goods 商品信息
     * @return 结果
     */
    @Override
    public boolean checkGoodsUnique(Goods goods)
    {
        Long goodsId = StringUtils.isNull(goods.getGoodsId()) ? -1L : goods.getGoodsId();
        Goods info = goodsMapper.checkGoodsUnique(goods);
        if (StringUtils.isNotNull(info) && info.getGoodsId().longValue() != goodsId.longValue())
        {
            return DictConstants.NOT_UNIQUE;
        }
        return DictConstants.UNIQUE;
    }

    /**
     * 新增保存商品信息
     * 
     * @param goods 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertGoods(Goods goods)
    {
        // 新增商品信息
        int rows = goodsMapper.insertGoods(goods);
        return rows;
    }

    /**
     * 修改保存商品信息
     * 
     * @param goods 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateGoods(Goods goods)
    {
        return goodsMapper.updateGoods(goods);
    }

    /**
     * 修改商品状态
     * 
     * @param goods 商品信息
     * @return 结果
     */
    @Override
    public int updateGoodsStatus(Goods goods)
    {
        return goodsMapper.updateGoods(goods);
    }

    /**
     * 批量删除商品信息
     * 
     * @param goodsIds 需要删除的商品ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteGoodsByIds(Long[] goodsIds) { return goodsMapper.deleteGoodsByIds(goodsIds); }

    /**
     * 导入商品数据
     * 
     * @param goodsList 商品数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作商品
     * @return 结果
     */
    @Override
    public String importGoods(List<Goods> goodsList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(goodsList) || goodsList.size() == 0)
        {
            throw new ServiceException("导入商品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Goods goods : goodsList)
        {
            try
            {
                // 验证是否存在这个商品
                Goods u = goodsMapper.checkGoodsUnique(goods);
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, goods);
                    goods.setCreateBy(operName);
                    goodsMapper.insertGoods(goods);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品 " + goods.getGoodsTitle() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, goods);
                    goods.setGoodsId(u.getGoodsId());
                    goods.setUpdateBy(operName);
                    goodsMapper.updateGoods(goods);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品 " + goods.getGoodsTitle() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、商品 " + goods.getGoodsTitle() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、商品 " + goods.getGoodsTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
